package com.ffmpeg.camera;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/** 基本的摄像头预览类 */
@SuppressLint("ViewConstructor")
public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback, Camera.PreviewCallback {

	private SurfaceHolder mHolder;
	private Camera mCamera;
	private int nCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
	private String TAG = "camera";
	Activity mActivity;

	public CameraPreview(Context context) {
		super(context);
		mActivity = (Activity) context;

		// try {
		// // 打开像机
		// nCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
		// mCamera = Camera.open(nCameraId);
		// } catch (Exception e) {
		// // 摄像头不可用（正被占用或不存在）
		// e.printStackTrace();
		// return;
		// }

		// 安装一个SurfaceHolder.Callback，
		// 这样创建和销毁底层surface时能够获得通知。
		mHolder = getHolder();
		mHolder.addCallback(this);

		// 已过期的设置，但版本低于3.0的Android还需要
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// surface已被创建，现在把预览画面的位置通知摄像头
		try {
			// 打开像机
			nCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
			mCamera = Camera.open(nCameraId);
			mCamera.setPreviewDisplay(holder);
			mCamera.startPreview();
		} catch (IOException e) {
			Log.d(TAG, "Error setting camera preview: " + e.getMessage());
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// 释放摄像头预览对象
		mCamera.release();
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		String s = "surfacechanged:format:" + format + ";with:" + w + ";high:"
				+ h;
		Log.d(TAG, s);

		// 如果预览无法更改或旋转，注意此处的事件
		// 确保在缩放或重排时停止预览
		if (mHolder.getSurface() == null) {
			// 预览surface不存在
			return;
		}

		// 更改时停止预览
		try {
			mCamera.stopPreview();
		} catch (Exception e) {
			// 忽略：试图停止不存在的预览
		}

		// 调整视频与窗口的角度关系
		setCameraDisplayOrientation(mActivity, nCameraId, mCamera);

		// 以新的设置启动预览
		try {
			
			/*Parameters params = mCamera.getParameters();
			List<Integer> p = params.getSupportedPreviewFormats ();
			Iterator<Integer> it = p.iterator();
			while(it.hasNext())
			{
				String dS = "suppert format:" + it.next().toString();
				Log.d(TAG, dS);
			}
			List<Camera.Size> size = params.getSupportedVideoSizes();
			Iterator<Camera.Size> itSize = size.iterator();
			while(itSize.hasNext())
			{
				Camera.Size i = itSize.next();
				String sSize = "support video size:" + i.height + "*" + i.width;
				Log.d(TAG, sSize);
			}
			params.setPreviewFormat(ImageFormat.YV12);
			mCamera.setParameters(params);*/
			mCamera.setPreviewDisplay(mHolder);
			// mCamera.setPreviewCallbackWithBuffer(this);
			mCamera.setPreviewCallback(this);
			mCamera.startPreview();
		} catch (Exception e) {
			Log.d(TAG, "Error starting camera preview: " + e.getMessage());
		}
	}

	public static void setCameraDisplayOrientation(Activity activity,
			int cameraId, android.hardware.Camera camera) {
		android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
		android.hardware.Camera.getCameraInfo(cameraId, info);
		int rotation = activity.getWindowManager().getDefaultDisplay()
				.getRotation();
		int degrees = 0;
		switch (rotation) {
		case Surface.ROTATION_0:
			degrees = 0;
			break;
		case Surface.ROTATION_90:
			degrees = 90;
			break;
		case Surface.ROTATION_180:
			degrees = 180;
			break;
		case Surface.ROTATION_270:
			degrees = 270;
			break;
		}

		int result;
		if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
			result = (info.orientation + degrees) % 360;
			result = (360 - result) % 360; // compensate the mirror
		} else { // back-facing
			result = (info.orientation - degrees + 360) % 360;
		}
		camera.setDisplayOrientation(result);
	}

	@Override
	public void onPreviewFrame(byte[] data, Camera camera) {
		// TODO Auto-generated method stub
		int nFormat = camera.getParameters().getPreviewFormat();
		String s = "nFormat:" + nFormat;
		Log.d(TAG, s);

	}
}
